package org.jeecg.common.export;

import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVPrinter;
import org.jeecgframework.poi.excel.entity.params.ExcelExportEntity;

import javax.servlet.ServletOutputStream;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author gchiaway
 * 日期: 2022-04-21
 * 时间: 16:00
 */
public class CsvExportServer {

    /**
     * 根据Map创建对应的Csv
     *
     * @param out        输出流
     * @param entityList Excel对象Class
     * @param dataSet    Excel对象数据List
     */
    public static CSVPrinter exportCsv(ServletOutputStream out, List<ExcelExportEntity> entityList, List<Map<String, String>> dataSet) throws Exception {

        List<String> headerList = new ArrayList<>();
        for (ExcelExportEntity entity : entityList) {
            headerList.add(entity.getName());
        }
        CSVFormat csvFormat = CSVFormat.DEFAULT.withHeader(headerList.toArray(new String[0]));
        OutputStreamWriter osw = new OutputStreamWriter(out, "UTF-8");
        CSVPrinter csvPrinter = new CSVPrinter(osw, csvFormat);
        //组装行数据
        for (Map<String, String> record : dataSet) {
            List<String> recordStrList = new ArrayList<>();
            for (ExcelExportEntity entity : entityList) {
                recordStrList.add(record.get(entity.getKey().toString()));
            }
            //打印一行
            csvPrinter.printRecord(recordStrList);
        }
        return csvPrinter;
    }
}
